﻿using UnityConfiguration.Infrastructure;

using mpu = Microsoft.Practices.Unity;
using mpuu = Microsoft.Practices.Unity.Utility;

namespace UnityConfiguration
{
    public class Instance : InstanceValue, IContainerConfigurationCommand
    {
        private string _Name;
        /// <summary>
        /// Name to use when registering this instance. Optional.
        /// </summary>
        public string Name {
            get { return string.IsNullOrEmpty(_Name) ? string.Empty : _Name; }
            set { _Name = value; }
        }

        /// <summary>
        /// Execute this command against the given container.
        /// </summary>
        /// <remarks>
        /// Interface implementors will implement this method to
        /// apply configuration changes to the container.</remarks>
        /// <param name="container">The <see cref="IUnityContainer"/> to configure.</param>
        public void Configure(mpu.IUnityContainer container) {
            mpuu.Guard.ArgumentNotNull(container, "container");
            string nameToRegister = Name;

            // Config system returns empty string if not specified. Make sure it's null.
            if (string.IsNullOrEmpty(nameToRegister)) {
                nameToRegister = null;
            }

            object valueToRegister = CreateInstance();
            container.RegisterInstance(TypeToCreate, nameToRegister,
                valueToRegister, new mpu.ContainerControlledLifetimeManager());
        }
    }
}
